package com.agent.commons.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于JWT令牌的创建以及校验的工具类
 */
public class JWTUtil {
    private static final Logger log= LoggerFactory.getLogger(JWTUtil.class);
    /**
     * 密钥：Base64编码的密钥
     */
    private static final String SECRET = "eAzvOA8bSkeRQn1Tc1jazUGO1F7EsPVGbL0iv6NF41c";
    /**
     * ⽣成安全密钥：将⼀个Base64编码的密钥解码并创建⼀个HMAC SHA密钥。
     */
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET));

    /**
     * 生成JWT令牌
     */
    public static String createJwt(Map<String,Object> claim){
        return Jwts.builder()
                .addClaims(claim)//设置令牌负载
                .setIssuedAt(new Date())
                .signWith(SECRET_KEY)//签名
                .setExpiration(new Date(System.currentTimeMillis()+1000*60*60*24))
                .compact();
    }

    /**
     * 校验JWT令牌
     */
    public static Claims parseJwt(String jwt){
        if (!StringUtils.hasLength(jwt)){
            return null;
        }
        // 创建解析器, 设置签名密钥
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(SECRET_KEY);
        Claims claims = null;
        try {
            //解析token
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        }catch (Exception e){
            //签名验证失败
            log.error("解析令牌错误,jwt:{}", jwt, e);
        }
        return claims;
    }

    /**
     * 从token中获取⽤⼾ID
     */
    public static String getUserIdFromToken(String jwtToken) {
        Claims claims = JWTUtil.parseJwt(jwtToken);
        if (claims != null) {
            Map<String, Object> userInfo = new HashMap<>(claims);
            return (String)userInfo.get("userId");
        }
        return null;
    }

    /**
     * 从token中获取用户名
     */
    public static String getUserNameFromToken(String jwtToken){
        Claims claims = JWTUtil.parseJwt(jwtToken);
        if (claims != null) {
            Map<String, Object> userInfo = new HashMap<>(claims);
            return (String)userInfo.get("userName");
        }
        return null;
    }

    /**
     * 从token中获取用户身份
     */
    public static String getUserRoleFromToken(String jwtToken){
        Claims claims = JWTUtil.parseJwt(jwtToken);
        if (claims != null) {
            Map<String, Object> userInfo = new HashMap<>(claims);
            return (String)userInfo.get("userRole");
        }
        return null;
    }

}
